package com.example.demo.web.controller;

import com.example.demo.web.client.DemoClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@RestController
@RequestMapping("/demo")
public class DemoController {

    private final DemoClient demoClient;

    public DemoController(DemoClient demoClient) {
        this.demoClient = demoClient;
    }

    private static ThreadLocal<String> timeString = new ThreadLocal<>();

    @GetMapping("hi")
    public String sayHello(String name) {
        timeString.set(String.valueOf(System.currentTimeMillis()));
        System.out.println(timeString.get() + Thread.currentThread().getName());

        String result;
        if (Objects.equals("???", name)) {
            throw new UnsupportedOperationException("I don't known " + name);
        } else if (Objects.equals("remote", name)) {
            result = demoClient.remoteHi(name);
        } else {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            result = "Hi " + name + ", time is " + timeString.get() + Thread.currentThread().getName();
        }
        return result;
    }

    @GetMapping("status")
    public ResponseEntity<String> remoteHi(@RequestParam(name = "name") String name) {
        return ResponseEntity.status(404).body("Remote Hi " + name);
    }
}
